package com.liuxu.NoRoot;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class request {
private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
    OkHttpClient client = new OkHttpClient.Builder()
            .cookieJar(new CookieJar() {
                @Override
                public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
                    cookieStore.put(httpUrl.host(), list);
                }

                @Override
                public List<Cookie> loadForRequest(HttpUrl httpUrl) {
                    List<Cookie> cookies = cookieStore.get(httpUrl.host());
                    return cookies != null ? cookies : new ArrayList<Cookie>();
                }
            })
            .build();
    public String gettoken(String targat) throws IOException {
        String regex = "'csrfmiddlewaretoken' value='(.*?)'";
        Pattern p = Pattern.compile(regex);
        String responseData =getByOkHttp(targat);
        String csrf_token=null;
        Matcher buf_m = p.matcher(responseData);
        while (buf_m.find()) {
            csrf_token=buf_m.group(1);
        }
        return csrf_token;
    }

    public String postByOkHttp(String path, Map values) throws IOException {
                FormBody.Builder body = new FormBody.Builder();
                body.add("token", values.get("token").toString())
                        .add("id", values.get("id").toString())
                        .add("version", values.get("version").toString())
                        .add("csrfmiddlewaretoken",  values.get("csrfmiddlewaretoken").toString());
                Request request = new Request.Builder()
                        .url(path)
                        .post(body.build())
                        .build();
                Response response = client.newCall(request).execute();
                String responseData = response.body().string();
                return responseData;
    }
    public String getByOkHttp(String path) throws IOException {
        Request request = new Request.Builder()
                .url(path)
                .build();
        Response response = client.newCall(request).execute();
        String responseData = response.body().string();
        return responseData;
    }

    public String getjson(String data, String word) throws JSONException {
            JSONObject jsonObject = new JSONObject(data);
        String result = jsonObject.getString(word);
            return result;
    }
}
